package Dao;

import Entity.Merchant;
import Entity.User;

import java.sql.*;
import java.util.*;

public class UserDao {
    private static Connection connection = null;

    private static void openDB() throws ClassNotFoundException, SQLException {
        // JDBC访问MySQL数据库
        // 1. 将连接MySQL的Jar包引入到工程中
        // 2. 加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 3. 获取数据库连接
        connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/ecommerce?characterEncoding=utf-8&serverTimezone=GMT%2B8",
                "root",
                "lty63481960");
    }

    private static void closeDB() throws SQLException {
        connection.close();
    }

    public static Map<String,String> queryall() throws SQLException, ClassNotFoundException {
        openDB();
        // 4. 编写查询city表的sql语句
        String sql = "select * from userinfo";
        // 5. 创建Statement
        Statement statement = connection.createStatement();
        // 6. 执行Statement
        ResultSet resultSet = statement.executeQuery(sql);
        // 7. 处理结果集
        Map<String,String> map = new HashMap<>();
        while (resultSet.next()) {
            String username = resultSet.getString("username");
            String password = resultSet.getString("password");

            map.put(username,password);
        }

        resultSet.close();
        statement.close();
        closeDB();

        return map;
    }

    public static void save(User user) throws SQLException, ClassNotFoundException {
        openDB();
        // 4. 编写查询city表的sql语句
        String sql = "insert into userinfo (username, password) value (?, ?)";
        // 5. 创建PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        // 6. 设置参数
        preparedStatement.setString(1, user.getUsername());
        preparedStatement.setString(2, user.getPassword());

        // 7. 执行插入
        preparedStatement.execute();

        // 8. 关闭资源
        preparedStatement.close();
        closeDB();
    }
}
